package com.project.im.web.service;

import com.project.im.app.dto.WebUserDetails;
import com.project.im.infra.entity.WebUser;
import com.project.im.infra.service.WebUserService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Component
@RequiredArgsConstructor
public class WebUserDetailService implements UserDetailsService {

    private final WebUserService webUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        WebUser webUser = webUserService.getByUsername(username);
        if (webUser == null) {
            return null;
        }
        WebUserDetails userDetails = new WebUserDetails();
        userDetails.setId(webUser.getId());
        userDetails.setUsername(webUser.getUsername());
        userDetails.setPassword(webUser.getPassword());
        List<String> roles = Arrays.stream(StringUtils.split(webUser.getRoles(), ",")).map(v -> "ROLE_" + v).toList();
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(roles);
        userDetails.setAuthorities(authorities);
        userDetails.setEnabled(webUser.getEnabled());
        return userDetails;
    }
}
